<?php
/**
 * 后台验证权限中间件
 * ============================================================================
 * * COPYRIGHT 2016-2019 xhadmin.com , and all rights reserved.
 * * WEBSITE: http://www.xhadmin.com;
 * ----------------------------------------------------------------------------
 * This is not a free software!You have not used for commercial purposes in the
 * premise of the program code to modify and use; and publication does not allow
 * any form of code for any purpose.
 * ============================================================================
 * Author: 寒塘冷月 QQ：274363574
 */

namespace app\admin\http\middleware;
use app\admin\db\Config as ConfigDb;
use think\facade\Config;
use think\facade\Cache;

class Check
{
	
    public function handle($request, \Closure $next)
    {	
		$admin = session('admin');
        $userid = session('admin_sign') == data_auth_sign($admin) ? $admin['userid'] : 0;
        if( !$userid && ( $request->app() <> 'admin' || $request->controller() <> 'Login' )){
			return redirect('admin/Login/index');
        }
		
		//验证权限
		list($app, $controller, $action) = [$request->app(), $request->controller(), $request->action()];
		$url =  "/{$app}/{$controller}/{$action}";
		
        /*不需要检测的权限*/		
		$nocheck = config('my.nocheck');
		if(session('admin.role') !== 1 && !in_array($url,$nocheck) && $action !== 'startImport'){
			if($controller <> 'Formdata'){
				if(!in_array($url,session('admin.nodes'))){
					return json(['status'=>'01','msg'=>'你没权限访问']);
				}	
			}else{
				//表单管理权限单独检测
				$extend_id = $request->param('extend_id','','intval');
				if(!in_array('/admin/FormData/'.$action.'/extend_id/'.$extend_id.'.html',session('admin.nodes')) && $action <> 'getExtends'){
					return json(['status'=>'01','msg'=>'你没权限访问']);
				}
			}
		}
		
		$key = 'xhadmin:config';
		if(Cache::get($key)){
			Config::set(Cache::get($key),'xhadmin');
		}else{
			$list = ConfigDb::loadList();
			Config::set($list,'xhadmin');
			Cache::set($key,$list,60);
		}
		
		//写入配置
		
        return $next($request);
    }
}